<template>
    <div class="box">
        <canvas id="three"></canvas>
    </div>
</template>
<!-- three.js -->
<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as THREE from 'three'
import * as Stats from 'stats.js'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

const stats = new Stats()
stats.showPanel(0) // 0: fps, 1: ms, 2: mb, 3+: custom
document.body.appendChild(stats.dom)

// 创建场景
const initThree = () => {
    const scene = new THREE.Scene()
    scene.background = new THREE.Color('#eee')

    const canvas = document.getElementById('three')
    const renderer = new THREE.WebGLRenderer({ canvas, antialias: true })

    const camera = new THREE.PerspectiveCamera(
        50,
        window.innerWidth / window.innerHeight,
        1,
        1000
    )

    const material = new THREE.MeshPhongMaterial({ color: 0x00ffff, transparent: true, opacity: 0.5 });
    const geometry = new THREE.BoxGeometry(100, 100, 100)


    const mesh = new THREE.Mesh(geometry, material)
    mesh.position.set(50, 50, 50)
    scene.add(mesh)

    const light = new THREE.DirectionalLight(0xffffff, 1)
    light.position.set(200, 200, 200)
    scene.add(light)

    let axishelper = new THREE.AxesHelper(250)
    scene.add(axishelper)

    camera.position.z = 1000
    const controls = new OrbitControls(camera, renderer.domElement)
    controls.enableDamping = true
    function animate() {
        renderer.render(scene, camera)
        stats.update()
        requestAnimationFrame(animate)

        if (resizeRendererToDisplaySize(renderer)) {
            const canvas = renderer.domElement
            camera.aspect = canvas.clientWidth / canvas.clientHeight
            camera.updateProjectionMatrix()
        }
    }
    animate()

    function resizeRendererToDisplaySize(renderer) {
        // 窗口自适应
        const canvas = renderer.domElement
        var width = window.innerWidth
        var height = window.innerHeight
        var canvasPixelWidth = canvas.width / window.devicePixelRatio
        var canvasPixelHeight = canvas.height / window.devicePixelRatio

        const needResize = canvasPixelWidth !== width || canvasPixelHeight !== height
        if (needResize) {
            renderer.setSize(width, height, false)
        }
        return needResize
    }
}
onMounted(() => {
    console.log(THREE)
    initThree()
})

onUnmounted(() => {
    stats.end()
})
</script>
<style lang="scss" scoped>
.box {
    width: 100vw;
    height: 100vh;
    overflow: hidden;
    box-sizing: border-box;
}

#three {
    width: 100%;
    height: 100%;
}
</style>
